﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Automapping; 
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System.IO;
using System.Reflection;
using System.Xml;

namespace SGMDev.Data_Extender
{
    public sealed class MySessionFactory
    {
        private static MySessionFactory CurrentInstance;
        private static ISessionFactory OpenSessionManager;
        private static object syncLock = new object();

        protected MySessionFactory()

        {
        }

        public static ISessionFactory InstantiedSession()
        {
            if (CurrentInstance == null)
            {
                lock (syncLock)
                {
                    if (CurrentInstance == null)
                    {
                        CurrentInstance = new MySessionFactory();
                        OpenSessionManager = CurrentInstance.CreateSessionFactory();
                    }
                }
            }
            return OpenSessionManager;
        }

        private ISessionFactory CreateSessionFactory()
        {
            Assembly assembly;
            assembly = Assembly.GetExecutingAssembly();

            var cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure(GetType().Assembly, "SGMDev.Data_Extender.hibernate.cfg.xml"
); // read config default style
            
            return Fluently.Configure(cfg)
              .Mappings(m => m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.Load("SGMDev.Entities")))
              .ExposeConfiguration(BuildSchema)
              .BuildSessionFactory();
        }

        private void BuildSchema(Configuration config)
        {
            new SchemaExport(config).Create(false, true);
        }

        //private void UpdateSchema(Configuration config)
        //{
        //    new SchemaExport(config).Execute(false, true, false);
        //}
    }
}